package com.z.redis.command.impl.string;

import com.z.redis.RedisCore;
import com.z.redis.command.CommandType;
import com.z.redis.command.WriteCommand;
import com.z.redis.datatype.BytesWrapper;
import com.z.redis.datatype.RedisString;
import com.z.redis.resp.BulkString;
import com.z.redis.resp.Resp;
import com.z.redis.resp.SimpleString;
import io.netty.channel.ChannelHandlerContext;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * MSET key1 value1 key2 value2 .. keyN valueN
 * 批量设置多个键值对
 */
public class Mset implements WriteCommand {
    private List<BytesWrapper> kvList;

    @Override
    public CommandType type(){
        return CommandType.mset;
    }
    @Override
    public void setContent(Resp[] array){
        kvList = Stream.of(array)
                .skip(1)
                .map(resp -> ((BulkString) resp).getContent())
                .collect(Collectors.toList());
    }

    @Override
    public void handle(ChannelHandlerContext ctx, RedisCore redisCore){
        for(int i=0;i<kvList.size();i+=2) { // 一个键一个值
            BytesWrapper key = kvList.get(i);
            BytesWrapper value = kvList.get(i+1);
            redisCore.put(key, new RedisString(value));
        }
        ctx.writeAndFlush(SimpleString.OK);
    }

    public void handle(RedisCore redisCore){
        for(int i=0;i<kvList.size();i+=2) { // 一个键一个值
            BytesWrapper key = kvList.get(i);
            BytesWrapper value = kvList.get(i+1);
            redisCore.put(key, new RedisString(value));
        }
    }
}
